package com.liduanwei.update.app;

import com.liduanwei.update.entity.AppInfo;
import com.liduanwei.update.entity.RemoteAppInfo;
import com.liduanwei.update.util.OSUtil;
import com.liduanwei.update.util.PrintUtil;
import com.liduanwei.update.util.PropertiesUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Wei on 17/10/3.
 * 自身版本检查
 */
public class SelfVersionChecker extends AbstractChecker {
    static String propertiesFile = "./self_version.properties";
    static Properties properties;

    static {
        properties = PropertiesUtil.Companion.loadProperties(propertiesFile);
        if (properties.isEmpty()) {
            properties.setProperty("version_code", "1");
            properties.setProperty("version_name", "1.0.0");
            PropertiesUtil.Companion.storeProperties(properties, propertiesFile);
        }
        PrintUtil.Companion.print("=========== [ 自身版本信息:" + properties + " ]");
    }

    @Override
    protected AppInfo loadCurrentAppInfo() {
        Properties properties = PropertiesUtil.Companion.loadProperties(propertiesFile);
        int versionCode = Integer.parseInt(properties.getProperty("version_code", "1"));
        String versionName = properties.getProperty("version_name", "1.0.0");
        return new AppInfo(versionCode, versionName);
    }

    RemoteAppInfo loadRemoteAppInfo() {
        return this.lastRemoteAppInfo;
    }

    boolean checkExpire() {
        return true;//return new Date().getTime() - lastCheckDate.getTime() >= 1000 * 60 * 60 * 2;
    }

    @Override
    protected void onNewestVersionComplete(boolean isSuccessfully) {
        super.onNewestVersionComplete(isSuccessfully);


        if (isSuccessfully && lastRemoteAppInfo != null) {
            properties.setProperty("version_code", lastRemoteAppInfo.getVersionCode() + "");
            properties.setProperty("version_name", lastRemoteAppInfo.getVersionName());
            PropertiesUtil.Companion.storeProperties(properties, propertiesFile);

            Map<String, String> data = new HashMap<>();
            data.put("selfVersionName", lastRemoteAppInfo.getVersionName());
            data.put("selfVersionCode", lastRemoteAppInfo.getVersionCode() + "");
            AppService.updateVersionToServer(data);

            if (!AppService.hasDownloadingTask()) {/*需要检查当前有无其它更新下载任务在执行中, 确保不会对其造成中止*/
                try {

                    System.out.println("=========restarting...==============");

                    String shFile = OSUtil.Companion.isLinux() ? "/media/yao/xxx/jinru/Updater/restart.sh" : "./restart.bat";
                    OSUtil.Companion.exec(shFile);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
